<template>
  <div class="main-container">
    <!-- tab导航 -start-->
    <slot v-if="xTabs == 'custom'" name="page-tabs" />
    <edu-page-tabs v-else :tab-list="xTabs">
      <!-- <template> -->
      <!-- 操作按钮 -start-->
      <!-- <div class="secret-item">
         <i class="edu-icon-shezhihover"></i>
         配置
       </div>
       <div class="secret-item">
         <i class="edu-icon-dingdan"></i>
         查看帮助
       </div> -->
      <!-- 操作按钮 -end-->
      <!-- </template> -->
    </edu-page-tabs>
    <!-- tab导航 -end-->

    <div class="add-form">
      <el-form ref="admin_form" :model="form" label-width="200px" size="medium">
        <el-form-item
          v-for="(vo, index) in pageKey"
          v-show="checkShowCondition(vo)"
          :key="index"
          :ref="'form.item.' + vo.key"
          :rules="getItemRules(vo)"
          :prop="vo.key"
        >
          <template v-slot:label>
            <span>{{ vo.title }}</span>
            <!--<el-popover v-if="vo.args.helpinfo" trigger="hover" transition="el-zoom-in-bottom" placement="top" popper-class="popper">-->
            <!--  <div v-html="vo.args.helpinfo" />-->
            <!--  <template v-slot:reference>-->
            <!--    <i class="edu-icon-info" />-->
            <!--  </template>-->
            <!--</el-popover>-->
          </template>
          <!-- 纯文字 -->
          <edu-word v-if="vo.type == 'word'" :key="vo.key" :value.sync="form[vo.key]" :args="vo.args" />
          <!-- 输入框 -->
          <!-- @update:value="$emit('change:' + vo, key, { value: form[vo.key], data: form })" -->
          <edu-input v-if="vo.type == 'input'" :key="vo.key" :value.sync="form[vo.key]" :args="vo.args" />
          <!-- 文本域 -->
          <edu-textarea v-else-if="vo.type == 'textarea'" :key="vo.key" :value.sync="form[vo.key]" :args="vo.args" />
          <!-- 计数器 -->
          <edu-input-number v-else-if="vo.type == 'input_number'" :key="vo.key" :value.sync="form[vo.key]" :args="vo.args" />
          <!-- 密码框 -->
          <edu-input-password v-else-if="vo.type == 'input_password'" :key="vo.key" :value.sync="form[vo.key]" :args="vo.args" />
          <!-- 单选 -->
          <edu-radio v-else-if="vo.type == 'radio'" :key="vo.key" :options="getOptions(vo.args.options, vo.key)" :value.sync="form[vo.key]" :args="vo.args" />
          <!-- 多选 -->
          <edu-checkbox v-else-if="vo.type == 'checkbox'" :key="vo.key" :options="getOptions(vo.args.options, vo.key)" :value.sync="form[vo.key]" :args="vo.args" />
          <!-- 下拉框 -->
          <edu-select v-else-if="vo.type == 'select'" :key="vo.key" :options="getOptions(vo.args.options, vo.key)" :value.sync="form[vo.key]" :args="vo.args" :disabled="true" />
          <!-- 多级 -->
          <edu-cascader v-else-if="vo.type == 'cascader'" :key="vo.key" :options="getOptions(vo.args.options, vo.key)" :value.sync="form[vo.key]" :args="vo.args" />
          <!-- 开关 -->
          <edu-switch v-else-if="vo.type == 'switch'" :key="vo.key" :value.sync="form[vo.key]" :args="vo.args" />
          <!-- 滑块 -->
          <edu-slider v-else-if="vo.type == 'slider'" :key="vo.key" :value.sync="form[vo.key]" :args="vo.args" />
          <!-- 评分 -->
          <edu-rate v-else-if="vo.type == 'rate'" :key="vo.key" :value.sync="form[vo.key]" :args="vo.args" />
          <!-- 日期-date -->
          <edu-date v-else-if="vo.type == 'date'" :key="vo.key" :options="getOptions(vo.args.options, vo.key)" :value.sync="form[vo.key]" :args="vo.args" />
          <!-- 时间-time -->
          <edu-time v-else-if="vo.type == 'time'" :key="vo.key" :options="getOptions(vo.args.options, vo.key)" :value.sync="form[vo.key]" :args="vo.args" />
          <!-- 颜色 -->
          <edu-color v-else-if="vo.type == 'color'" :key="vo.key" :value.sync="form[vo.key]" :args="vo.args" />
          <!-- 上传 -->
          <edu-upload
            v-else-if="vo.type == 'upload'"
            :key="vo.key"
            :field="vo.key"
            :value.sync="form[vo.key]"
            :args="vo.args"
            :file-list="form[vo.key + '_list']"
            @file:event="fileEvent(vo.key, $event)"
          />
          <!-- tag -->
          <edu-tag v-else-if="vo.type == 'tag'" :key="vo.key" :value.sync="form[vo.key]" :args="vo.args" />
          <!-- 编辑器 -->
          <edu-editor v-else-if="vo.type == 'editor'" :key="vo.key" :value.sync="form[vo.key]" :args="vo.args" />
          <!-- 搜索机构 -->
          <edu-search-school v-else-if="vo.type == 'search_school'" :key="vo.key" :value.sync="form[vo.key]" :args="vo.args" :form-datas="form" />
          <!-- 自定义 -->
          <div v-else-if="vo.type == 'custom'">
            <component
              :is="customComponents[vo.key]"
              :key="vo.key"
              :value.sync="form[vo.key]"
              :args="vo.args"
              :field="vo.key"
              :form-datas="form"
              @update:data="updateData"
              @change="validateField(vo.key)"
            />
          </div>
          <div v-else><span v-text="vo.args.placeholder" /></div>
          <div v-if="vo.args.helpinfo" class="edu-tips" v-html="vo.args.helpinfo"></div>
        </el-form-item>
        <!-- <el-form-item>
          <el-button
            type="primary"
            :disabled="disableSubmit"
            @click="onSubmit"
            v-if="saveBtnText !== false"
            v-text="saveBtnText"
          ></el-button> -->
        <!-- <el-button @click="resetForm" v-if="resetBtnText" v-text="resetBtnText"></el-button> -->
        <!-- </el-form-item> -->
        <div class="suspend-wrapper">
          <div class="suspend-placeholder" />
          <div class="suspend-fixed">
            <el-button v-if="saveBtnText !== false" type="primary" :disabled="disableSubmit" size="medium" @click="onSubmit" v-text="saveBtnText" />
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import EduPageTabs from './tabs/page_tabs.vue';
import EduWord from '../form/word.vue';
import EduInput from '../form/input.vue';
import EduTextarea from '../form/textarea.vue';
import EduInputNumber from '../form/input_number.vue';
import EduInputPassword from '../form/input_password.vue';
import EduRadio from '../form/radio.vue';
import EduCheckbox from '../form/checkbox.vue';
import EduSelect from '../form/select.vue';
import EduCascader from '../form/cascader.vue';
import EduSwitch from '../form/switch.vue';
import EduSlider from '../form/slider.vue';
import EduRate from '../form/rate.vue';
import EduDate from '../form/date.vue';
import EduTime from '../form/time.vue';
import EduColor from '../form/color.vue';
import EduUpload from '../form/upload.vue';
import EduEditor from '../form/editor.vue';
import EduTag from '../form/tag.vue';
import EduSearchSchool from '@/pages/school/choose';

export default {
  components: {
    EduPageTabs,
    EduWord,
    EduInput,
    EduTextarea,
    EduInputNumber,
    EduInputPassword,
    EduRadio,
    EduCheckbox,
    EduSelect,
    EduCascader,
    EduSwitch,
    EduSlider,
    EduRate,
    EduDate,
    EduTime,
    EduColor,
    EduUpload,
    EduEditor,
    EduTag,
    EduSearchSchool
  },
  inject: ['reload'],
  props: {
    xUri: {
      type: String,
      required: true
    },
    xParams: {
      type: Object,
      default: _ => {
        return {};
      }
    },
    xTabs: {
      type: [Array, String],
      default: 'custom'
    },
    // 默认选项配置
    bindOptions: {
      type: Object,
      default: _ => {
        return {};
      }
    },
    // 默认数据
    bindData: {
      type: Object,
      default: _ => {
        return {};
      }
    },
    // 禁用提交按钮
    disableSubmitBtn: {
      type: Boolean,
      default: false
    },
    // 默认验证方法
    bindRules: {
      type: Object,
      default: _ => {
        return {};
      }
    },
    // 提交方法,如果指定了该参数,则进行自定义提交方法处理
    bindSubmit: {
      type: Function,
      default: null
    },
    // 提交处理成功之后跳转路由
    redirect: {
      type: String,
      default: ''
    },
    // 重置按钮显示文字
    // resetBtnText: {
    //   type: [String, Boolean],
    //   default: false
    // },
    // 保存按钮显示文字
    saveBtnText: {
      type: [String, Boolean],
      default: '保存'
    },
    // 自定义组件
    customComponents: {
      type: Object,
      default: _ => {
        return {};
      }
    },
    // 字段显示条件
    showCondition: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      form: {
        ...this.bindData
      },
      form_options: this.bindOptions,
      disableSubmit: this.disableSubmitBtn
    };
  },
  computed: {
    ...mapState('pageForm', {
      pageData: 'responseData'
    }),
    // 表单字段配置数据
    ...mapState('pageForm/pagekey', {
      pageKey: 'pagekeyList'
    })
  },
  watch: {
    pageData(pageData) {
      const data = {
        ...this.form,
        ...pageData.datas,
        ...this.bindData
      };

      this.$set(this, 'form', data);
    },
    disableSubmitBtn(status) {
      this.disableSubmit = status;
    }
  },
  created() {
    this.$store.dispatch('pageForm/page', { uri: this.xUri, params: this.xParams });
  },
  methods: {
    // 控制验证规则
    getItemRules: function(field) {
      if (this.$util.isDef(this.bindRules[field.key])) {
        return this.bindRules[field.key];
      }
      if (field.args.required) {
        return [{ required: true, message: field.title + '为必填项', trigger: ['blur', 'change'] }];
      }

      return null;
    },
    // 获取表单字段选项
    getOptions: function(options, field) {
      if (this.$util.getDefValue(options, false)) {
        return options;
      }
      if (this.$util.isDef(this.form_options[field])) {
        return this.form_options[field];
      }
      return [];
    },
    // 重置表单值
    resetForm: function() {
      this.$refs['admin_form'].resetFields();
      this.disableSubmit = false;
    },
    // 提交
    onSubmit: function() {
      this.$refs['admin_form'].validate((valid, object) => {
        if (valid) {
          if (this.$util.isFunction(this.bindSubmit)) {
            return this.bindSubmit(this.form);
          }
          this.disableSubmit = true;
          this.$http.send(
            this.pageData.saveMethod,
            this.pageData.savePostUrl,
            {
              ...this.pageData.datas,
              ...this.form
            },
            response => {
              this.$message.success(response.msg, _ => {
                if (this.redirect) {
                  this.$router.push({ path: this.redirect });
                } else {
                  this.reload();
                }
              });
            },
            error => {
              this.disableSubmit = false;
              this.$message.error(error.msg);
            }
          );
        } else {
          this.scrollView(object);
        }
      });
    },
    // 上传事件触发,父组件使用 @upload:字段名 监听
    fileEvent: function(field, event) {
      this.$emit('upload:' + field, event);
    },
    updateData: function(data) {
      this.$set(this.form, data.field, data.value);
    },
    scrollView: function(object) {
      for (const i in object) {
        let dom = this.$refs['form.item.' + i];
        // 这里是针对遍历的情况（多个输入框），取值为数组
        if (Object.prototype.toString.call(dom) !== '[object Object]') {
          dom = dom[0];
        }
        // 第一种方法（包含动画效果）
        dom.$el.scrollIntoView({
          // 滚动到指定节点
          // 值有start,center,end，nearest，当前显示在视图区域中间
          block: 'center',
          // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          behavior: 'smooth'
        });
        break; // 因为我们只需要检测一项,所以就可以跳出循环了
      }
    },
    validateField: function(field) {
      this.$refs['admin_form'].validateField(field);
    },
    // 检测是否显示字段
    checkShowCondition(field) {
      const checkFuntion = this.showCondition ? this.showCondition[field.key] : null
      if (this.$util.isFunction(checkFuntion)) {
        return !!checkFuntion(this.form, field, this.pageKey)
      }

      return true
    }
  }
};
</script>

<style lang="scss" scoped>
.add-form {
  ::v-deep .el-input {
    // width: 100%;
    .el-input__inner {
      border-radius: 0;
    }
  }
  ::v-deep .el-form-item__label {
    padding: 0 24px 0 0;
  }

  .data-line {
    float: left;
    width: 20px;
    text-align: center;
  }
  // 上传头像
  .avatar-uploader {
    ::v-deep .el-upload {
      width: 110px;
      height: 110px;
      border: 1px dashed rgba(192, 196, 204, 1);
      cursor: pointer;
      position: relative;
      overflow: hidden;
      &:hover {
        border-color: #409eff;
      }
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 110px;
      height: 110px;
      line-height: 111px;
      text-align: center;
    }
    .avatar-img {
      width: 110px;
      height: 110px;
      display: block;
    }
  }
}
.edu-icon-info {
  cursor: help;
}
.suspend-wrapper {
  .suspend-placeholder {
    height: 80px;
  }
  .suspend-fixed {
    height: 55px;
    position: fixed;
    left: 231px;
    right: 0;
    bottom: 0;
    z-index: 10;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fff;
    border-top: 1px solid #e4e7ed;
    .el-button--medium {
      padding: 10px 30px;
    }
  }
}
</style>
